# Maintainer: Biswapriyo Nath <nathbappai@gmail.com>

_realname=libpcap
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.10.4
pkgrel=1
pkgdesc="A system-independent interface for user-level packet capture (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
url="https://www.tcpdump.org/"
license=('spdx:BSD-3-Clause')
depends=("${MINGW_PACKAGE_PREFIX}-openssl")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=("https://www.tcpdump.org/release/${_realname}-${pkgver}.tar.gz"{,.sig}
        "0001-cmake-install-rpcapd-bindir.patch"
        "0002-cmake-keep-lib-prefixed-dll.patch"
        "0003-charconv-include-errno.patch")
sha256sums=('ed19a0383fad72e3ad435fd239d7cd80d64916b87269550159d20e47160ebe5f'
            'SKIP'
            'c3b177c92d76fd0300b1d2d1cb7975f9dc393d5c0286d83a3e22bfdafdf265f4'
            '09dfe0f962a99df7d1d8fdb9bb9b320b6d33e0a7c2efec136065a7b359de188d'
            '8a7faa97e85adc8fb532499205224e94e4d2b77693e42666f6c2bd48c9f38571')
validpgpkeys=('1F166A5742ABB9E0249A8D30E089DEF1D9C15D0D') # The Tcpdump Group

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"
  patch -Np1 -i "${srcdir}/0001-cmake-install-rpcapd-bindir.patch"
  patch -Np1 -i "${srcdir}/0002-cmake-keep-lib-prefixed-dll.patch"
  patch -Np1 -i "${srcdir}/0003-charconv-include-errno.patch"
}

build() {
  mkdir -p "${srcdir}/build-${MSYSTEM}" && cd "${srcdir}/build-${MSYSTEM}"

  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G "Ninja" \
    -Wno-dev \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    "${_extra_config[@]}" \
    -DDISABLE_DBUS=ON \
    "../${_realname}-${pkgver}"

  ${MINGW_PREFIX}/bin/cmake.exe --build ./
}

check() {
  cd "${srcdir}/build-${MSYSTEM}"
  ${MINGW_PREFIX}/bin/ctest.exe ./ || true
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --install .

  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  for pcfile in "${pkgdir}${MINGW_PREFIX}"/lib/pkgconfig/*.pc; do
    sed -s "s|${PREFIX_WIN}|${MINGW_PREFIX}|g" -i "${pcfile}"
  done
  sed -s "s|${PREFIX_WIN}|${MINGW_PREFIX}|g" -i "${pkgdir}${MINGW_PREFIX}"/bin/pcap-config

  install -Dm644 "${srcdir}/${_realname}-${pkgver}/LICENSE" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
